
<template>
    <div>
        <van-nav-bar :title="route.meta.title" left-arrow @click-left="router.back()" fixed placeholder />
        <van-address-list v-model="addressId" :list="addressStore.data" default-tag-text="默认" @add="onAdd" @edit="onEdit"
            @select="onSelect" />

    </div>
</template>
    
<script setup>
import { useRoute, useRouter } from 'vue-router';
import { useAddressStore } from '@/stores/address.js'
import { ref } from 'vue'
//默认地址的id
let addressId = ref('')

let addressStore = useAddressStore()

const route = useRoute()
const router = useRouter();


let onAdd = () => {
    if (route.query.goodsInfo) {
        //如果有参数说明是购买操作，把商品信息暂存起来，如果去添加地址页面后还要回到地址页，会导致路由参数消失
        sessionStorage.setItem('goodsinfo', route.query.goodsInfo)
    }
    router.push({ name: 'addAddress' })
}
let onEdit = (item, index) => {
    router.push({
        name: 'addAddress', query: {
            data: btoa(encodeURI(JSON.stringify(addressStore.list[index]))),
        }
    })
}

let onSelect = (res) => {
    if (route.query.goodsInfo) {
        let data = JSON.parse(decodeURI(atob(route.query.goodsInfo)))
        router.push({
            name: 'createOrder',
            query: {
                orderInfo:
                    btoa(encodeURI(JSON.stringify({
                        goods: data,
                        adress: res
                    })))
            }
        })
    } else if (sessionStorage.getItem('goodsinfo')) {
        let data = JSON.parse(decodeURI(atob(sessionStorage.getItem('goodsinfo'))))
        router.push({
            name: 'createOrder',
            query: {
                orderInfo:
                    btoa(encodeURI(JSON.stringify({
                        goods: data,
                        adress: res
                    })))
            }
        })
    }
}

//监听pinia中数据变化
addressStore.$subscribe((mutation, state) => {
    let obj = state.data.find(item => {
        return item.isDefault == true
    })
    //可能会出现地址列表有数据但所有地址的默认选择都为false，找不到返回undefined，要对这种情况做处理
    if (obj) {
        addressId.value = obj.id
    } else {
        addressId.value = 0
    }
}, { immediate: true })

</script>
    
<style  scoped></style>